package com.code.demo.ui;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;

import com.code.demo.R;
import com.code.demo.databinding.ActivitySplashBinding;
import com.code.demo.eventbus.EventUpdate;
import com.code.demo.bean.Update;
import com.code.demo.novate.NovateClient;
import com.code.demo.permission.PermissionManager;
import com.code.demo.ui.base.BaseActivity;
import com.code.demo.ui.common.DialogNormal;
import com.code.demo.ui.common.DialogUpdate;
import com.code.demo.ui.guide.GuideActivity;
import com.code.demo.update.UpdateManager;
import com.code.demo.util.SharedPreferencesUtil;
import com.yanzhenjie.permission.Permission;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;

import static com.code.demo.config.HandlerEvent.ACTIVITY_FINISHED;
import static com.code.demo.config.HandlerEvent.PERMISSION_FAIL;
import static com.code.demo.config.HandlerEvent.PERMISSION_SUCCESS;
import static com.code.demo.config.StorageKey.last_version_code;
import static com.code.demo.config.StorageKey.splash_hide_alert;

/**
 * Created by yangliguo on 2018/3/7.
 */

public class SplashActivity extends BaseActivity {

    private ActivitySplashBinding binding;
    private SharedPreferencesUtil sp;
    private boolean invisableAlert = true;
    private DialogUpdate dialog;
    private Update updateInfo;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case ACTIVITY_FINISHED:
                    alert();
                    break;
                case PERMISSION_SUCCESS:
                    success();
                    break;
                case PERMISSION_FAIL:
                    fail();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_splash);
        binding.setInvisableAlert(invisableAlert);
        binding.setPresenter(new Presenter());

        mHandler.sendEmptyMessageDelayed(ACTIVITY_FINISHED, 1500);
        sp = SharedPreferencesUtil.getInstance(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventUpdate event) {
        if (event != null && event.getUpdate() != null) {
            //如果apk已经下载好就提示，否则直接进下一页
            updateInfo = event.getUpdate();
            if (UpdateManager.getUpdateManager(this).checkApkFile(updateInfo)) {
                showDialog();
            } else {
                ready();
            }
        } else {
            ready();
        }
    }

    public void showDialog() {
        dialog = new DialogUpdate(this, updateInfo.getUpdateMsg());
        dialog.positive.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                UpdateManager.getUpdateManager(SplashActivity.this).installApk();
                dialog.dismiss();
            }
        });
        dialog.negative.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (updateInfo.getForce() == 1) {
//                    finish();
                    ready();
                } else {
                    ready();
                }

                dialog.dismiss();
            }
        });
        dialog.show();
    }

    private void alert() {
        invisableAlert = sp.getBoolean(splash_hide_alert);
        binding.setInvisableAlert(invisableAlert);

        //第一次启动时候，需要显示提醒权限的UI，所以不能立即请求权限控制，要等到用户关闭对话框才能开始请求
        if (invisableAlert) {
            if (Build.VERSION.SDK_INT >= 23) {
                new PermissionManager(this, mHandler).requestPermission(
                        Permission.Group.PHONE,
                        Permission.Group.STORAGE
                );
            } else {
                success();
            }
        }
    }

    private void success() {
        ready();
//        //检查新版本
//        try {
//            String pkName = getPackageName();
//            String versionName = getPackageManager().getPackageInfo(
//                    pkName, 0).versionName;
//
//            Map<String, Object> map = new HashMap<>();
//            map.put("appType", "android");
//            map.put("currentVersion", versionName);
////            map.put("packageName", pkName);
//            map.put("packageName", "com.qibu.child");
//            new NovateClient(this, "checkVersion").post(map);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    private void fail() {
        DialogNormal dialog = new DialogNormal(this, "", "您必须同意您才能正常使用本app", "再试一次", "退出应用");
        dialog.positive.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                if (Build.VERSION.SDK_INT >= 23) {
                    new PermissionManager(SplashActivity.this, mHandler).requestPermission(
                            Permission.Group.PHONE,
                            Permission.Group.STORAGE
                    );
                } else {
                    success();
                }
            }
        });
        dialog.negative.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                finish();
            }
        });
        dialog.show();
    }

    public void ready() {

        //是否需要显示引导页
        try {
            int code = getPackageManager().getPackageInfo(
                    getPackageName(), 0).versionCode;

            int lastCode = sp.getInt(last_version_code);
            sp.putInt(last_version_code, code);
            if (code > lastCode) {
                startActivity(new Intent(SplashActivity.this, GuideActivity.class));
            } else {
                startActivity(new Intent(SplashActivity.this, MainActivity.class));
            }
            finish();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public class Presenter {

        public void onClose() {
            invisableAlert = true;
            sp.putBoolean(splash_hide_alert, invisableAlert);
            binding.setInvisableAlert(invisableAlert);

            if (Build.VERSION.SDK_INT >= 23) {
                //第一次启动时候，需要显示提醒权限的UI，所以不能立即请求权限控制，要等到用户关闭对话框才能开始请求
                new PermissionManager(SplashActivity.this, mHandler).requestPermission(
                        Permission.Group.PHONE,
                        Permission.Group.STORAGE
                );
            } else {
                success();
            }
        }
    }
}
